#!/usr/sbin/rsct/perl5/bin/perl 
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1999,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# "@(#)07   1.20   src/rsct/registry/cli/bin/rmsrtbl.perl, srcli, rsct_rpyxh, rpyxht1f3 2/22/01 16:25:33"
######################################################################
#                                                                    #
# Module: rmsrtbl                                                    #
#                                                                    #
# Purpose:                                                           #
#   rmsrtbl - Removes System Registry tables.                        #
#                                                                    #
# Syntax:                                                            #
#   rmsrtbl [-h][-TV] Table ...                                      #
#                                                                    #
# Flags:                                                             #
#   -h      Help - writes this command's usage statement to stdout   #
#   -T      Trace - writes this command's trace statements to stderr #
#   -V      Verbose - writes this command's verbose statements to    #
#                     stderr                                         #
#                                                                    #
# Operands:                                                          #
#   Table       Name of the table to be deleted from the System      #
#               Registry. One or more Table operand can be specified.#
#               An absolute or relative path name can be used.       #
#                                                                    #
# Description:                                                       #
#   The rmsrtbl command allows you to remove one or more tables      #
#   from the System Registry. If more than one Table is specified,   #
#   it is equivalent to calling the command once for each Table name.#
#   Both the table data and definition are removed.                  #
#                                                                    #
#   Use the lssr (srls) command to get a current listing of tables   #
#   contained in a specified System Registry directory.              #
#                                                                    #
#   You must have write permission on the directory you wish to      #
#   delete the table from.                                           #
#                                                                    #
# Exit Values:                                                       #
#   0  SR_CLI_SUCCESS        Command completed successfully.         #
#   1  SR_CLI_REGISTRY_ERROR Command terminated due to an underlying #
#                            System Registry error.                  #
#   2  SR_CLI_ERROR          Command terminated due to an underlying #
#                            error in the command script.            #
#   3  SR_CLI_BAD_OPERAND    Command terminated due to user          #
#                            specifying a bad operand.               #
#   4  SR_CLI_BAD_FLAG       Command terminated due to user          #
#                            specifying an invalid flag.             #
#   5  SR_CLI_USER_ERROR     Command terminated due to a user error. #
#                            For example specifying an undefined     #
#                            table to be removed.                    #
#                                                                    #
# Examples:                                                          #
#   1. To delete multiple tables if the CT_SR_HOME environment       #
#   variable is set to /samples, enter:                              #
#       rmsrtbl table1 table2                                        #
#                                                                    #
#                                                                    #
#   2. To delete a single table using an absolute specification      #
#   enter:                                                           #
#       rmsrtbl /system/Table3                                       #
#                                                                    #
#--------------------------------------------------------------------#
# Inputs:                                                            #
#                                                                    #
# Outputs:                                                           #
#       stdout - display of information messages                     #
#       stderr - display of error messages                           #
#                                                                    #
# External Ref:                                                      #
#   Commands: $LSMSG                                                 #
#   Extensions:  CT::SR.pm CT::SRrc.pm                               #
#   Perl library routines: Getopts::Std                              #
#   SR cli library routines: SR_cli_utils - init_session, error_exit #
#                set_session_variables, term_session, printCEMsg     #
#                            SR_cli_rc - CLI return codes            #
#   Environment variables:  SR_HOME                                  #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   000929 HGJ 38317: Initial delivery.                              #
#                                                                    #
######################################################################

#--------------------------------------------------------------------#
#                                                                    #
# General Progam/Logic flow for rmsrtbl:                             #
#                                                                    #
#   A: Parse command line                                            #
#   B: Initialize session with registry - change current directory   #
#       based on absolute or relatvie path name given, and the       #
#       value of CT_SR_HOME, if necessary.                           #
#   C: Delete table, using CT::SR::delete_table                      #
#   D: Clean up tree used for session                                #
#                                                                    #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# Included Libraries and Extensions                                  #
#--------------------------------------------------------------------#
use lib "/usr/sbin/rsct/pm";
use locale;
use Getopt::Std;

use CT_cli_utils qw(printIMsg
                    printEMsg
);

use CT::SR;
use CT::SRrc;
use SR_cli_utils qw(init_session 
                    term_session printCEMsg
                    $DEFAULT_GLOBAL_MOUNT_POINT
                    error_exit   set_session_variables
);
use SR_cli_rc qw(:return_codes);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
# Constants
$TRUE           = 1;
$FALSE          = 0;

# Other Global Variables
$Verbose        = $FALSE;
$Trace          = $FALSE;

# Messaging variables
$PROGNAME       = "rmsrtbl";           # Program Name for messages
$MSGCAT         = "srcli.cat";         # msg catalogue for this cmd
$CTDIR          = "/usr/sbin/rsct";    # Cluster directory path
$CTBINDIR       = "$CTDIR/bin";        # Cluster Bin directory path
$LSMSG          = "$CTBINDIR/ctdspmsg"; # display message rtn.
$ENV{'MSGMAPPATH'} = "$CTDIR/msgmaps"; # msg maps used by $LSMSG  

%Cleanup = ();                         # Hash of items to cleanup
                                       # {Session} $session to term


#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
my $Tree_handle    = "";                  # initialised in initSession

my $Mount_point    = $DEFAULT_GLOBAL_MOUNT_POINT;
my $Set_work_dir   = $FALSE;
my @Table_name     = ();
my @Table          = ();        
my $rc             = 0;
my $badrc          = 0;


#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#
# TODO: Many verbose statements in this code will eventually by
# Trace statements when the facility is available as a Perl CLI
# (feature 48401). The existing Trace statements
# TODO: security on access to the table can not be further defined
# until after a security design has been implemented for the SR.
# ( feature 48402 ) Until then, the table is opened with the
# minimum security necessary to complete the command.


# Parse the command line, exit if there are errors
($rc, @Table_name) = parse_cmd_line();
($rc == 0) || error_exit($rc);

# Initialize variables for initSession - check to see if an
# absolute or relative table name has been passed in.
# Fully qualify absolute table names. If any relative
# names are passed in, then set the current working directory.
my $index = 0;
foreach (@Table_name) {
    ($holder, $Table[$index]) = set_session_variables($_);
    if ($holder == $TRUE) {$Set_work_dir = $TRUE};
    $index++;
}


# Initialize session with registry and set the current directory
# if CT_SR_HOME is set
# If one of the tables requires the current working directory to
# be set, then it is set. (Determined in the previous foreach loop)
($rc, $Tree_handle) = init_session( $Set_work_dir );
($rc == 0) || error_exit($rc);

# Add the tree handle to the cleanup hash
$Cleanup{Session} = $Tree_handle;


# Attempt to delete each table in the list. Report an error if 
# necessary, keep the highest error code to return
foreach (@Table) {
    $Verbose && printIMsg("IMsgrmsrtblRemovingTable", $_);

    # Call C API to delete the table 
    $Trace && print STDERR "Calling CT::SR::delete_table\n";
    $rc = CT::SR::delete_table($Tree_handle, $_);
    $Trace && print STDERR "CT::SR::delete_table return code: $rc\n";

    # Strip off any leading internal references to /SR for
    # messaging purposes
    my $table = $_;
    $table =~ s/^\/SR//;
    $rc = error_check("sr_delete_table", $rc, $table);

    # Continue to remove tables, unless a System Registry
    # error occurred, in which case the code has already quit. 
    if ($rc == SR_CLI_REGISTRY_ERROR) {
        $badrc = $rc;
        last;
    }
    # Save the first bad return code
    if (($rc != 0) && ($badrc == 0)) { $badrc = $rc; }
}

# Quit gracefully
($badrc == 0) || error_exit($badrc);  

# Continue and try to exit gracefully from the session
$rc = term_session($Tree_handle, $Mount_point);

exit $rc;

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# parse_cmd_line:                                                    #
#   Uses getopts() to grab flags on the command line, including an   #
#   input file name if the '-f' flag is used.                        #
#                                                                    #
# Return values:                                                     #
#   $local_rc   - return code.                                       #
#   @table_name - array of tables names to be deleted                #
#                                                                    #
# Global variables modified:                                         #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#--------------------------------------------------------------------#
sub parse_cmd_line
{
my $local_rc = 0;
my @table_name = ();
my $index = 0;
my %opts = ();    

if (getopts('hTV', \%opts) == 0) {   # parse input flags  
    printCEMsg("EMsgSRcliInvalidFlag");
    print_usage();  
    return SR_CLI_BAD_FLAG;      
}

if (defined $opts{h}) {         # print usage and exit
    print_usage();   
    exit(0);
}

if (defined $opts{T}) {         # -T turns trace on
    $Trace = $TRUE;     
}

if (defined $opts{V}) {         # -V turns verbose mode on
    $Verbose = $TRUE;     
}

# Grab the table name(s) from the command line or report an error
# if there aren't any
if (@ARGV) {
    # Load the output array with tables to be processed.
    while (@ARGV) { 
        $table_name[$index++] = shift @ARGV;
    }
}
else {
    printCEMsg("EMsgSRcliNoTableName");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

return ($local_rc, @table_name); 
}   # end parse_cmd_line


#--------------------------------------------------------------------#
# error_check:                                                       #
#   Checks the return code from the SR function.  If an error is     #
#   detected appropriate error messages will be displayed and        #
#   SR CLI return code set.                                          #
#                                                                    #
# Parameters:                                                        #
#   $sr_function  - Name of the SR function that was called and      #
#                   whose error code we are checking.                #
#   $sr_rc        - SR function return code.                         #
#   $table_name   - Name of the SR table.                            #
#                                                                    #
# Return values:                                                     #
#   None.                                                            #
#                                                                    #
# Global References:                                                 #
#   None.                                                            #
#--------------------------------------------------------------------#
sub error_check
{
my ($sr_function, $sr_rc, $table_name) = @_;
my $rc = 0;

if ($sr_rc != 0) {
    if ($sr_rc == SR_NO_PERMISSION) {
        printEMsg("EMsgrmsrtblNoPermission", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_TABLE) {
        printEMsg("EMsgrmsrtblNoTable", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_TABLE_LOCKED) {
        printEMsg("EMsgrmsrtblTableLocked", $table_name);
        $rc = SR_CLI_USER_ERROR
    }
    elsif ($sr_rc == SR_CONNECTION_LOST) {
        printCEMsg("EMsgSRcliConnectionLost");
        $rc = SR_CLI_REGISTRY_ERROR;
    }
    else {
        printEMsg("EMsgrmsrtblErrorRemovingTable", $table_name,
            $sr_rc); 
        printCEMsg("EMsgSRcliSRCommandFailure", $sr_function, $sr_rc);
        $rc = SR_CLI_REGISTRY_ERROR;
    }
}

return ($rc);
}   # end error_check


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#   See this command's prologue syntax section for current usage.    #
#--------------------------------------------------------------------#
sub print_usage
{
printIMsg("IMsgrmsrtblUsage");
}   # end print_usage


#--------------------------------------------------------------------#
#  End File                                                          #
#--------------------------------------------------------------------#
